package com.aps.apspda.activity;

import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.aps.apspda.R;
import com.aps.apspda.adapter.CheckInputDataListAdapter;
import com.aps.apspda.base.BaseActivity;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.callback.StringCommonCallBack;
import com.aps.apspda.dialog.ChooseCheckFragmentDialog;
import com.aps.apspda.dialog.DeleteFragmentDialog;
import com.aps.apspda.dialog.GeneralPop;
import com.aps.apspda.dialog.WarnFragmentDialog;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.CheckEntity;
import com.aps.apspda.entity.FinishLotEntity;
import com.aps.apspda.entity.InputDataEntity;
import com.aps.apspda.entity.InputDatasEntity;
import com.aps.apspda.myview.ClearEditText;
import com.aps.apspda.myview.TitleView;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class CheckActivity extends BaseActivity {


    @BindView(R.id.topView)
    TitleView topView;
    @BindView(R.id.rvCheckList)
    RecyclerView rvCheckList;
    @BindView(R.id.tvEqpId)
    TextView tvEqpId;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvSkipTips)
    TextView tvSkipTips;
    @BindView(R.id.toggleButton)
    ToggleButton toggleButton;
    @BindView(R.id.etSkipReason)
    ClearEditText etSkipReason;
    @BindView(R.id.llSkip)
    LinearLayout llSkip;

    private CheckInputDataListAdapter checkInputDataListAdapter;
    private List<InputDatasEntity.InputObjects> inputList;
    private String checkType;
    private boolean isConfirmSubmit = false;
    private View.OnClickListener submitClick;
    private String instruction = "";
    private boolean isSkip = false;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_check;
    }

    @Override
    protected void initView() {
        topView.setTitle("日检&周检(" + StaticMembers.CUR_USER.getUSERNAME() + ")");
        //add by bunny 返回按钮增加消息给EAP
        topView.setLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final DeleteFragmentDialog deleteFragmentDialog = new DeleteFragmentDialog();
                deleteFragmentDialog.setData("确定返回主界面吗？", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (AntiShake.check(v.getId())) {    //判断是否多次点击
                            ToastUtils.showFreeToast("请勿重复点击",
                                    CheckActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                        deleteFragmentDialog.dismiss();
                        checkReturn();
                    }
                });
                deleteFragmentDialog.show(getSupportFragmentManager(), "checkReturn_dialog");
            }
        });
        //end
        submitClick = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String skipReason = etSkipReason.getText().toString().trim();
                if (isSkip && skipReason.length() == 0) {
                    ToastUtils.showFreeToast("请填写跳过点检的原因", CheckActivity.this, false, Toast.LENGTH_SHORT);
                    return;
                }
                if (checkInputDataListAdapter != null) {
                    boolean isOk = true;
                    List<InputDataEntity.InputObject> dataList = checkInputDataListAdapter.getDataList();
                    // bunny 点击提交，焦点停留在第一个*未填写内容上 start
                    for (InputDataEntity.InputObject inputObject : dataList) {
                        inputObject.setISFOCUS(Boolean.FALSE);
                    }
                    //end
                    if (!isSkip) {
                        for (InputDataEntity.InputObject inputObject : dataList) {
                            if (inputObject.getDATACHTITLE().length() == 0) {
                                if (inputObject.getISNULL().equalsIgnoreCase("Y") &&
                                        inputObject.getDATAVALUE().length() == 0) {
                                    ToastUtils.showFreeToast("请填写带*栏数据", CheckActivity.this, false, Toast.LENGTH_SHORT);
                                    // bunny 点击提交，焦点停留在第一个*未填写内容上 start
                                    inputObject.setISFOCUS(Boolean.TRUE);
                                    rvCheckList.scrollToPosition(inputObject.getPosition());
                                    checkInputDataListAdapter.notifyDataSetChanged();
                                    return;
                                    //end
                                } else {
                                    if (inputObject.getDATAVALUE().toUpperCase().contains("NG") || inputObject.getDATAVALUE().contains("其他")) {
                                        String[] strs = inputObject.getDATAVALUE().split(";");
                                        if (strs.length <= 1) {
                                            isOk = false;
                                            ToastUtils.showFreeToast("请给NG或其他项填写原因", CheckActivity.this, false, Toast.LENGTH_SHORT);
                                        }
                                    }
                                }
                                if (!isOk) {
                                    break;
                                }
                            }
                        }
                    }
                    inputList = new ArrayList<>();
                    for (InputDataEntity.InputObject object : dataList) {
                        if (object.getDATACHTITLE().length() != 0) {
                            InputDatasEntity.InputObjects objects = new InputDatasEntity.InputObjects();
                            objects.setDATACNNAME(object.getDATACHTITLE());
                            objects.setDATANAME(object.getDATATITLE());
                            objects.setPosition(object.getPosition());
                            List<InputDataEntity.InputObject> list = new ArrayList<>();
                            InputDataEntity entity = new InputDataEntity();
                            entity.setINPUTDATA(list);
                            objects.setINPUTDATAS(entity);
                            inputList.add(objects);
                        }
                    }
                    for (InputDatasEntity.InputObjects objects : inputList) {
                        for (InputDataEntity.InputObject object : dataList) {
                            if (object.getDATACHTITLE().length() == 0) {
                                if (objects.getPosition() == object.getPosition()) {
                                    List<InputDataEntity.InputObject> list = objects.getINPUTDATAS().getINPUTDATA();
                                    list.add(object);
                                    objects.getINPUTDATAS().setINPUTDATA(list);
                                }
                            }
                        }
                    }
                    if (isOk) {
                        requestInputData();
                    }
                }
            }
        };
        rvCheckList.setLayoutManager(new LinearLayoutManager(CheckActivity.this));
        rvCheckList.setItemAnimator(new DefaultItemAnimator());
        rvCheckList.addItemDecoration(new DividerItemDecoration(CheckActivity.this, 1));
        final ChooseCheckFragmentDialog chooseCheckFragmentDialog = new ChooseCheckFragmentDialog();
        chooseCheckFragmentDialog.setCallBack(new StringCommonCallBack() {
            @Override
            public void onCallback(String str) {
                checkType = str;
                tvSkipTips.setText(checkType.equals("DAY") ? "是否跳过日检：" : "是否跳过周检：");
                requestData();
                chooseCheckFragmentDialog.dismissDialog();
            }
        });
        chooseCheckFragmentDialog.show(getSupportFragmentManager(), "chooseCheckType_dialog");
    }

    @Override
    protected void initData() {
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                etSkipReason.setText("");
                if (isChecked) {
                    isSkip = true;
                    etSkipReason.setVisibility(View.VISIBLE);
                } else {
                    isSkip = false;
                    etSkipReason.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }

    private void requestInputData() {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(CheckActivity.this)) {
                    if (!isConfirmSubmit) {
                        toggleButton.setChecked(false);
                        etSkipReason.setVisibility(View.GONE);
                        etSkipReason.setText("");
                        requestData();
                    } else {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                CheckActivity.this.finish();
                            }
                        }, 1000);
                    }
                    loadSuccess(response.body().getMessage());
                } else {
                    loadFail(response.body().getMessage());
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "SubmitInputData");
            }
        };

        Map<String, String> map = new HashMap<>();
        JSONArray jsonArray2 = new JSONArray();
        try {
            for (InputDatasEntity.InputObjects objects : inputList) {
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("DATACNNAME", objects.getDATACNNAME());
                jsonObject2.put("DATANAME", objects.getDATANAME());
                if (objects.getINPUTDATAS().getINPUTDATA().size() == 0) {
                    jsonObject2.put("INPUTDATAS", new JSONObject().put("INPUTDATA", ""));
                } else {
                    JSONArray jsonArray = new JSONArray(new Gson().toJson(objects.getINPUTDATAS().getINPUTDATA()));
                    jsonObject2.put("INPUTDATAS", new JSONObject().put("INPUTDATA", jsonArray));
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("INPUTDATA", jsonObject2);
                jsonArray2.put(jsonObject);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        map.put("InputDataList", jsonArray2.toString());
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        map.put("EqpId", getEqpID());
        map.put("InputDataType", checkType.equals("DAY") ? "CHECKDAY" : "CHECKWEEKS");
        map.put("SkipReason", isSkip ? "OK;"+etSkipReason.getText().toString().trim() : "NG;");
        NetUtils.requestNet(this, "/SubmitInputData", map, callBack);
    }

    private void requestData() {
        EntityCallBack<BaseEntity<CheckEntity>> callBack = new DialogEntityCallBack<BaseEntity<CheckEntity>>(
                (new TypeToken<BaseEntity<CheckEntity>>() {
                }.getType()), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<CheckEntity>> response) {
                if (response.body().isSuccess(CheckActivity.this)) {
                    CheckEntity checkEntity = response.body().getData();
                    instruction = checkEntity.getINSTRUCTIONS();
                    tvEqpId.setText(checkEntity.getEQPID());
                    tvType.setText(checkEntity.getCHECKTYPE());
                    if (checkEntity.getSKIP().toUpperCase().equals("T")) {
                        llSkip.setVisibility(View.VISIBLE);
                    } else {
                        llSkip.setVisibility(View.GONE);
                    }
                    if (checkEntity.getTOREQUEST().toUpperCase().equals("A")) {
                        topView.setRightListener("提交", submitClick);
                        isConfirmSubmit = false;
                    } else {
                        topView.setRightListener("确认提交", submitClick);
                        isConfirmSubmit = true;
                    }
                    List<InputDataEntity.InputObject> dataList = new ArrayList<>();
                    List<InputDatasEntity.InputObjects> inputObjects = checkEntity.getINPUTDATALIST().getINPUTDATA();
                    for (int i = 0; i < inputObjects.size(); i++) {
                        InputDatasEntity.InputObjects objects = inputObjects.get(i);
                        InputDataEntity.InputObject inputObject = new InputDataEntity.InputObject();
                        inputObject.setDATATITLE(objects.getDATANAME());
                        inputObject.setDATACHTITLE(objects.getDATACNNAME());
                        inputObject.setPosition(i + 1);
                        dataList.add(inputObject);
                        List<InputDataEntity.InputObject> list = objects.getINPUTDATAS().getINPUTDATA();
                        for (InputDataEntity.InputObject object : list) {
                            object.setPosition(inputObject.getPosition());
                        }
                        dataList.addAll(list);
                    }
                    checkInputDataListAdapter = new CheckInputDataListAdapter();
                    checkInputDataListAdapter.setDataList(dataList);
                    rvCheckList.setAdapter(checkInputDataListAdapter);
                } else {
                    //loadFail();
                    //modify by bunny  fail后返回主界面
                    final WarnFragmentDialog dialog = new WarnFragmentDialog();
                    dialog.setData(response.body().getMessage());
                    dialog.setListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                            CheckActivity.this.finish();
                        }
                    });
                    dialog.show(getSupportFragmentManager(), "check_fail_tips");
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<CheckEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ShowCheckC2E");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", getEqpID());
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        map.put("CHECKTYPE", checkType);
        NetUtils.requestNet(this, "/ShowCheckC2E", map, callBack);
    }


    @OnClick({R.id.ivMessage,})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivMessage:
                LayoutInflater inflater = LayoutInflater.from(this);
                View popView = inflater.inflate(R.layout.popupwindow_text, null);
                final GeneralPop titlePop = new GeneralPop(this, popView
                        , (int) (StaticMembers.SCREEN_WIDTH * 0.8), (int) (StaticMembers.SCREEN_HEIGHT * 0.8)
                        , R.style.BottomDialog);
                titlePop.showAtLocation(llMain, Gravity.CENTER, 0, 0);
                TextView tvMessage = popView.findViewById(R.id.tvMessage);
                ImageView ivClose = popView.findViewById(R.id.ivClose);
                ivClose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        titlePop.dismiss();
                    }
                });
                tvMessage.setText(Html.fromHtml(instruction));
                break;
        }
    }
    private void checkReturn() {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(CheckActivity.this)) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            CheckActivity.this.finish();
                        }
                    }, 1000);
                    loadSuccess(response.body().getMessage());
                } else {
                    loadFail(response.body().getMessage());
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "CheckReturn");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", getEqpID());
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        map.put("CHECKTYPE", tvType.getText().toString());
        if(isConfirmSubmit){
            map.put("TOREQUEST", "B");
        }
        else {
            map.put("TOREQUEST", "A");
        }
        NetUtils.requestNet(this, "/CheckReturn", map, callBack);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            final DeleteFragmentDialog deleteFragmentDialog = new DeleteFragmentDialog();
            deleteFragmentDialog.setData("确定返回主界面吗？", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (AntiShake.check(v.getId())) {    //判断是否多次点击
                        ToastUtils.showFreeToast("请勿重复点击",
                                CheckActivity.this, false, Toast.LENGTH_SHORT);
                        return;
                    }
                    deleteFragmentDialog.dismiss();
                    checkReturn();
                }
            });
            deleteFragmentDialog.show(getSupportFragmentManager(), "checkReturn_dialog");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
